from pathlib import Path
from typing import Union

__all__ = ['FileProcessor']

from utils._files import (
    JsonProcessor as _JsonProcessor,
    NfoProcessor as _NfoProcessor,
    YamlProcessor as _YamlProcessor,
    IniProcessor as _IniProcessor,
)


class _FileLoader:
    """小文件读取"""

    def json(self) -> _JsonProcessor:
        """读取json文件"""
        return _JsonProcessor(self.path)

    def nfo(self) -> _NfoProcessor:
        """读取nfo文件"""
        return _NfoProcessor(self.path)

    def yaml(self) -> _YamlProcessor:
        """读取yaml文件"""
        return _YamlProcessor(self.path)

    def ini(self) -> _IniProcessor:
        return _IniProcessor(self.path)

    def load_data(self):
        suffix = self.path.suffix.strip('.').lower()
        suffix = 'yaml' if suffix in ['yaml', 'yml'] else suffix
        try:
            load_func = getattr(self, suffix)
            return load_func()
        except AttributeError:
            raise ValueError(f"不支持的后缀类型: {suffix}")

    def __new__(
            cls,
            path: str,
            suffix: str = None,
            *args,
            **kwargs
    ) -> Union[_NfoProcessor, _JsonProcessor, _YamlProcessor, _IniProcessor]:
        # 1.处理路径输入
        if not isinstance(path, Path):
            path = Path(path)
        # 2.后缀拼接，后缀.json 或 json 都行
        if suffix:
            path = path.with_suffix(suffix if '.' in suffix else '.' + suffix)
        # 3. 验证文件存在
        if not path.exists():
            raise FileExistsError(path)
        # 4. 创建实例但不调用__init__
        instance = super().__new__(cls)
        # 5. 直接设置实例变量（跳过__init__）
        instance.path = path
        # 6. 返回处理器实例
        return instance.load_data()


class _FileSaver(_FileLoader):

    def __new__(
            cls,
            path: str,
            suffix: str = None,
            *args,
            **kwargs
    ) -> Union[_NfoProcessor, _JsonProcessor, _YamlProcessor, _IniProcessor]:
        # 1.处理路径输入
        if not isinstance(path, Path):
            path = Path(path)
        # 2.后缀拼接，后缀.json 或 json 都行
        if suffix:
            path = path.with_suffix(suffix if '.' in suffix else '.' + suffix)
        # 3. 验证文件目录不存在,则创建目录
        if not path.parent.exists():
            path.parent.mkdir(parents=True, exist_ok=True)
        # 4. 创建实例但不调用__init__
        instance = object.__new__(cls)
        # 5. 直接设置实例变量（跳过__init__）
        instance.path = path
        # 6. 返回处理器实例
        return instance.load_data()


class FileProcessor:
    def __new__(
            cls,
            path: Union[str, Path],
            /,
            suffix: str = None,
            model='r',
            *args,
            **kwargs
    ) -> Union[_NfoProcessor, _JsonProcessor, _YamlProcessor, _IniProcessor]:
        """
        :param model 读取模式还是写入模式，区别在于读模式校验文件路径；写模式自动创建文件的目录
        """
        if model in ('r', 'read', 'r+', 'rb'):
            return _FileLoader(path, suffix, *args, **kwargs)
        return _FileSaver(path, suffix, *args, **kwargs)


if __name__ == '__main__':
    file = _FileSaver(r'E:\PythonProject\yunCoolCinema\data\CJOD-342-C.json')
    file.save(data={'a': 1, 'b': 2})
